package com.erp.purchase.service.impl;

import com.erp.purchase.domain.Product;
import com.erp.purchase.domain.PurOrderDTO;
import com.erp.purchase.domain.PurOrderItem;
import com.erp.purchase.service.IPurOrderAppendService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.erp.purchase.mapper.PurOrderAppendMapper;

import java.util.Date;
import java.util.List;

/**
 * --- 天道酬勤 ---
 *
 * @author hfw
 * @date 2025/9/5
 * @desc
 */
@Slf4j
@Service
public class PurOrderAppendServiceImpl implements IPurOrderAppendService {
    @Autowired
    private PurOrderAppendMapper purOrderAppendMapper;


    @Override
    public List<String> getProductCategoryList() {
        return purOrderAppendMapper.getProductCategoryList();
    }

    @Override
    public List<Product> getProductList(String productName) {
        return purOrderAppendMapper.getProductList(productName);
    }

    @Override
    public List<Product> getProductListByCategory(String category) {
        return purOrderAppendMapper.getProductListByCategory(category);
    }

    @Override
    public List<String> getWarehouseList() {
        return purOrderAppendMapper.getWarehouseList();
    }

    @Override
    public int addOrder(PurOrderDTO purOrderDTO) {
        //生成订单编号
        String orderNo = "PO" + new Date().getTime();
        purOrderDTO.getPurOrder().setOrderNo(orderNo);
        
        //先插入订单主表
        int i1 = purOrderAppendMapper.addOrder(purOrderDTO.getPurOrder());
        log.info("新增订单：{}", i1);
        
        if(i1 > 0) {
            //从数据库查订单id
            int orderId = purOrderAppendMapper.getOrderId(orderNo);
            log.info("查询到的订单ID：{}", orderId);
            
            //将订单id赋值给订单详情
            if(purOrderDTO.getPurOrderItems() != null && !purOrderDTO.getPurOrderItems().isEmpty()) {
                for (PurOrderItem purOrderItem : purOrderDTO.getPurOrderItems()) {
                    purOrderItem.setOrderId((long) orderId);
                }
                
                //插入订单详情
                int i2 = purOrderAppendMapper.addOrderItem(purOrderDTO.getPurOrderItems());
                log.info("新增订单详情：{}", i2);
                
                if(i2 > 0) {
                    return 1;
                }
            }
        }

        return 0;
    }
}